<template>
  <div class="mt-tabs" :id="id">
    <div
      class="mt-tab-item "
      :class="{ actived: isActived(index) }"
      v-for="(item, index) in list"
      :key="index"
      @click="tabClick(index)"
    >
      <span>{{ typeof item === 'string' ? item : item.label }}</span>
    </div>
    <div class="under-line" :style="underLineStyle"></div>
  </div>
</template>

<script>
  export default {
    props: {
      list: {
        type: Array,
        default: () => [],
      },
      value: {
        type: [String, Number],
        default: '',
      },
    },
    data() {
      return {
        underLineStyle: {},
        id: 'mt-tab-' + parseInt(Math.random() * 1e3),
      };
    },
    watch: {
      list() {
        this.initUnderLine(0);
      },
    },
    mounted() {
      this.initUnderLine(this.value || 0);
    },
    methods: {
      /**
       * 点击事件
       */
      tabClick(index) {
        // 如果是字符串,返回数组的索引, 不然返回value
        this.$emit(
          'input',
          typeof this.list[index] === 'string' || !this.list[index].value
            ? index
            : this.list[index].value,
        );
        this.initUnderLine(index);
      },
      initUnderLine(index) {
        const currentDom = document.querySelectorAll(`#${this.id} .mt-tab-item`)[index];
        if (!currentDom) return;
        const style = currentDom.getBoundingClientRect();
        const span = currentDom.querySelector('span');
        const spanStyle = currentDom.querySelector('span').getBoundingClientRect();
        this.underLineStyle = {
          left: (currentDom.offsetLeft + span.offsetLeft) / 10 + 'rem',
          width: spanStyle.width / 10 + 'rem',
        };
      },
      isActived(index) {
        return typeof this.list[index] === 'string'
          ? this.value === index
          : this.value === this.list[index].value;
      },
    },
  };
</script>

<style lang="less" scoped>
  .mt-tabs {
    display: flex;
    position: relative;
    font-size: 3.2rem;
    font-weight: 400;
    color: #ffffff;

    .mt-tab-item {
      margin-right: 5rem;
      padding-bottom: 2.4rem;
      position: relative;
      cursor: pointer;
      color: #ffffff;
      opacity: 0.5;

      &.actived,
      &:hover {
        opacity: 1;
      }
      &.actived {
        font-weight: 800;
      }
    }

    .under-line {
      content: '';
      display: block;
      position: absolute;
      left: 0;
      bottom: 0;
      height: 0.7rem;
      background: #fff;
      border-radius: 0.3rem;
      transition: all 0.2s;
    }

    // &:after {
    //   content: '';
    //   display: block;
    //   position: absolute;
    //   left: 0;
    //   right: 0;
    //   bottom: 0;
    //   height: .5rem;
    //   background: #ffffff;
    //   opacity: 0.1;
    //   border-radius: .3rem;
    // }
  }
</style>
